package com.jyb.qiyefuwu.viewmodel;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.jyb.qiyefuwu.api.EnterpriseServiceAPIManager;
import com.jyb.qiyefuwu.entity.OderDetailsEntity;
import com.jyb.qiyefuwu.entity.ServiceNodeBean;
import com.jyb.qiyefuwu.entity.ServiceOderContactsBean;
import com.jyb.qiyefuwu.entity.ServiceOderInvoiceBean;
import com.sgb.net.entity.BaseEntity;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.util.DateUtils;

import org.jsoup.helper.DataUtil;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SalesOderDetailsModel extends BaseViewModel {
    public MutableLiveData<OderDetailsEntity> oderData = new MutableLiveData<>();
    public MutableLiveData<String> dataText = new MutableLiveData<>();
    public MutableLiveData<String> checkData = new MutableLiveData<>();
    public ServiceOderContactsBean contactData = new ServiceOderContactsBean();
    public ServiceOderInvoiceBean invoiceData = new ServiceOderInvoiceBean();
    public MutableLiveData<String> updateMark = new MutableLiveData<>();
    public MutableLiveData<List<ServiceNodeBean>> nodeList = new MutableLiveData<>();

    private long midTime;
    private String info;
    public int buyerOrSeller;//表示从那跳转过来的，0是销售订单，1是采购订单


    public SalesOderDetailsModel(@NonNull Application application) {
        super(application);
    }

    /**
     * 商标订单详情
     *
     * @param orderId
     */
    public void tradeMark(String orderId, int buyOrSeller) {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().tradeMark(orderId, buyOrSeller).enqueue(new Callback<BaseEntity<OderDetailsEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<OderDetailsEntity>> call, Response<BaseEntity<OderDetailsEntity>> response) {
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    oderData.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<OderDetailsEntity>> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 专利订单详情
     *
     * @param orderId
     */
    public void patent(String orderId, int buyOrSeller) {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().patent(orderId, buyOrSeller).enqueue(new Callback<BaseEntity<OderDetailsEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<OderDetailsEntity>> call, Response<BaseEntity<OderDetailsEntity>> response) {
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    oderData.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<OderDetailsEntity>> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 版权订单详情
     *
     * @param orderId
     */
    public void copyrigh(String orderId, int buyOrSeller) {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().copyrigh(orderId, buyOrSeller).enqueue(new Callback<BaseEntity<OderDetailsEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<OderDetailsEntity>> call, Response<BaseEntity<OderDetailsEntity>> response) {
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    oderData.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<OderDetailsEntity>> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 切换联系人
     */
    public void saveOrUpdate() {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().saveOrUpdate(contactData).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    checkData.postValue("ok");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 选择开票信息
     */
    public void billingInformation() {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().billingInformation(invoiceData).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    checkData.postValue("ok");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 修改备注
     */
    public void updateNote(String id, String mark) {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().updateNote(id, mark).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    updateMark.postValue("ok");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 获取订单流程
     */
    public void process(String id) {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().process(id).enqueue(new Callback<BaseEntity<List<ServiceNodeBean>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<ServiceNodeBean>>> call, Response<BaseEntity<List<ServiceNodeBean>>> response) {
                if (response.body() == null && response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    nodeList.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<ServiceNodeBean>>> call, Throwable t) {
                String msg = t.getMessage();
            }
        });
    }

    /**
     * 倒计时
     *
     * @param time
     * @param info
     * @param sysTime
     */
    public void timeBefore(String time, String info, String sysTime) {
        String st = DateUtils.stampToDate(time);//结束或者开始时间
        String nt = DateUtils.stampToDate(sysTime + "");//当前时间
        String nts = DateUtils.stampToDate(System.currentTimeMillis()+"");//当前时间
        Timestamp t = Timestamp.valueOf(st);
        Timestamp n = Timestamp.valueOf(nt);
        if (n.before(t)) {
            //没过期
            long nl = System.currentTimeMillis();
            long sl = Long.valueOf(time);
            time2((sl - nl) / 1000, info);
        }/* else {
            mBinding.tvEndTime.setText("卖方接单超时，系统自动关闭订单");
            mBinding.tvStatus.setText("已关闭");
        }*/
    }

    public void time2(long midTime, String info) {
        this.midTime = midTime;
        this.info = info;
        removeTimer();
        timeHandler.postDelayed(runnable, 1000);
    }

    private Runnable runnable = new Runnable() {
        private String time;

        @Override
        public void run() {
            if (midTime > 0) {
                midTime--;
//                Calendar calendar =  Calendar.getInstance();
//                calendar.setTimeInMillis(midTime);
//
//                Log.e("messageTime",calendar.get(Calendar.DATE)+":"+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));
//                Log.e("messageTime", DateUtils.formatDate(new BigDecimal(Long.parseLong("1634290164164")).subtract(new BigDecimal(System.currentTimeMillis())).longValue(),"dd天HH小时mm分ss"));
                long dd = midTime / 86400;
                long hh = midTime % 86400 / 3600;                 //转换小时
                long mm = midTime % 86400 % 3600 / 60;            //转换分钟
                long ss = midTime % 86400 % 3600 % 60;            //剩余秒数
                if (dd > 0) {
                    time = dd + "天" + hh + "小时" + mm + "分钟" + ss + "秒" + info;
                } else {
                    if (hh > 0) {
                        time = hh + "小时" + mm + "分钟" + ss + "秒" + info;
                    } else {
                        if (mm > 0) {
                            time = mm + "分钟" + ss + "秒" + info;
                        } else {
                            time = ss + "秒" + info;
                        }
                    }
                }
                Message message = Message.obtain();
                message.what = 1;
                message.obj = time;
                timeHandler.sendMessage(message);
//                Log.e("倒计时", time);
                timeHandler.postDelayed(runnable, 1000);
            } else {
                timeHandler.removeCallbacks(runnable);
            }
        }
    };

    public void removeTimer() {
        if (runnable != null) {
            timeHandler.removeCallbacks(runnable);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                dataText.postValue((String) msg.obj);
            }
        }
    };

}
